package com.gaogzhen.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaogzhen.domain.SysPrivilege;
import com.gaogzhen.mapper.SysPrivilegeMapper;
import com.gaogzhen.service.SysPrivilegeService;
import org.springframework.util.CollectionUtils;

@Service
public class SysPrivilegeServiceImpl extends ServiceImpl<SysPrivilegeMapper, SysPrivilege> implements SysPrivilegeService{

    @Autowired
    private SysPrivilegeMapper sysPrivilegeMapper;

    @Override
    public List<SysPrivilege> getPrivileges(Long menuId, Long roleId) {
        // 查询菜单下所有权限
        List<SysPrivilege> privileges = new LambdaQueryChainWrapper<>(sysPrivilegeMapper)
                .eq(SysPrivilege::getMenuId, menuId)
                .list();
        if (CollectionUtils.isEmpty(privileges)) {
            return Collections.emptyList();
        }
        // 查询角色拥有的权限
        Set<Long> ids = sysPrivilegeMapper.getPrivilegesByRoleId(roleId);
        if (CollectionUtils.isEmpty(ids)) {
            return privileges;
        }
        // 把所有权限中当前角色权限own设置为1
        for (SysPrivilege privilege : privileges) {
            if (ids.contains(privilege.getId())) {
                privilege.setOwn(1);
            }
        }
        return privileges;
    }
}
